//
//  LoginViewController.m
//  KEREN
//
//  Created by MW on 2023/3/8.
//

#import "LoginViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "TouchDrawView.h"
#import "HomeViewController.h"
#import "KRTabarController.h"
#import "NSDictionary+Expand.h"
typedef NS_ENUM(NSInteger, loginType) {
    WXLogin  = 0  ,//微信登录
    appleLogin    ,//苹果登录
    passwordLogin ,//密码登录
    codeLogin     ,//验证码登录
    forgotPassword,//忘记密码
    setPassword   ,//修改密码
    bindPhone     ,//绑定手机号
};

@interface LoginViewController ()<UITextFieldDelegate>{
    NSInteger _second;
}
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) UIView *loginView;
@property (nonatomic, strong) UIImageView *logoImage;
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) UIButton *soundBtn;
@property (nonatomic, strong) UILabel *loginTitleLbl;
@property (nonatomic, strong) UIButton *LoginTypeBtn;
@property (nonatomic, strong) UITextField *photoField;
@property (nonatomic, strong) UITextField *codeField;
@property (nonatomic, strong) UIButton *loginBtn;
@property (nonatomic, strong) UILabel *forgetLab;
@property (nonatomic, strong) UILabel *rigisterLab;
@property (nonatomic, strong) UIButton *wxLoginBtn;
@property (nonatomic, strong) UIButton *appleLoginBtn;
@property (nonatomic, strong) UILabel *tipsLbl;
@property (nonatomic, strong) UIImageView *leftLineimageView;
@property (nonatomic, strong) UIImageView *rightLineimageView;
@property (nonatomic, strong) UILabel *attributeLbl;
@property (nonatomic, strong) UIButton *select_icon;
@property (nonatomic, assign) NSInteger loginType;
@property (nonatomic, strong) UIButton *codeBtn;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UIButton *seeBtn;
@property (nonatomic, copy) NSString *code;
@property (nonatomic, copy) NSString *phone;
@property (nonatomic, copy) NSString *appleId;
@property (nonatomic, assign) BOOL isbindWX;
@property (nonatomic, strong) MPVolumeView *volumeView;
@property (nonatomic, strong) UISlider *volumeViewSlider;
@property (nonatomic, assign) float val;
@end

@implementation LoginViewController
- (void)dealloc{
    DDLogInfo(@"============LoginViewController dealloc");
    [AVAudioSession.sharedInstance removeObserver:self forKeyPath:@"outputVolume" context:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //[[LoginManager sharedInstance] faceIdLogin];
    [self setupForAVplayerView];
    [self setViewLayout];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    //视频播放
    [center addObserver:self selector:@selector(playVideo) name:@"appBecomeActive" object:nil];
    //注册、接收通知
    [center addObserver:self selector:@selector(setPhonenumb:) name:SETPHONENUMB object:_appleId];
    
    
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session addObserver:self forKeyPath:@"outputVolume" options:NSKeyValueObservingOptionNew context:nil];

    _isbindWX = NO;
    NSString *phone = [[NSUserDefaults standardUserDefaults] objectForKey:USERPHONE];
    BOOL isFaceLogin = [[NSUserDefaults standardUserDefaults] boolForKey:[NSString stringWithFormat:@"isFaceIdLogin_%@",phone]];
    if(isFaceLogin){
        [[LoginManager sharedInstance] faceIdLogin];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqual:@"outputVolume"]) {
        NSLog(@"%@", change);
        float volume = [change floatForDict:@"new"];
        _soundBtn.selected = volume == 0;
    }
}

- (void)setViewLayout{
    // self.view.backgroundColor = [UIColor redColor];
    _logoImage = [[UIImageView alloc] initWithFrame:CGRectMake((DEVICE_WIDTH - 198) /2, 170 + STATUSBAR_HEIGHT, 198, 46)];
    _logoImage.image = [UIImage imageNamed:@"LOGO"];
    [self.view addSubview:_logoImage];
    //TODO 国际化
    UIButton *loginBtn = [UIButton setButtonWithTitle:@"登录/注册" titleColor:Color_20222F titleFont:BFont(16) cornerRadius:29 backColor:Whire_Color];
    [self.view addSubview:loginBtn];
    
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(24);
        make.right.offset(-24);
        make.height.offset(58);
        make.bottom.offset(-110);
    }];
    //TODO 国际化
    UIButton *reciveBtn = [UIButton setButtonWithTitle:@"虚拟体验" titleColor:Whire_Color titleFont:BFont(16) cornerRadius:29 backColor:white_Alpha(0, 0.75)];
    [self.view addSubview:reciveBtn];
    [reciveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(24);
        make.right.offset(-24);
        make.height.offset(58);
        make.bottom.offset(-36);
    }];
    [reciveBtn addTarget:self action:@selector(reciveBtnClick) forControlEvents:UIControlEventTouchUpInside];

    [loginBtn addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    _backBtn = [UIButton setButtonWithImage:@"back" cornerRadius:0 backColor:[UIColor clearColor]];
    [self.view addSubview:_backBtn];
    [_backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(40);
        make.left.offset(24);
        make.top.offset(9 + STATUSBAR_HEIGHT);
    }];
    [_backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    _backBtn.hidden = YES;
    
    //_soundBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _soundBtn = [UIButton setButtonWithImage:@"sound_icon" cornerRadius:0 backColor:[UIColor clearColor]];
    [self.view addSubview:_soundBtn];
    [_soundBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(40);
        make.right.offset(-24);
        make.top.offset(9 + STATUSBAR_HEIGHT);
    }];
    [_soundBtn addTarget:self action:@selector(soundBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_soundBtn setImage:[UIImage imageNamed:@"sound_close_icon"] forState:UIControlStateSelected];
    _soundBtn.selected = YES;
    _volumeView = [[MPVolumeView alloc] initWithFrame: CGRectZero];
    for(UIView *view in [self.volumeView subviews])
    {
        if([[[view class] description] isEqualToString:@"MPVolumeSlider"])
        {
            self.volumeViewSlider=(UISlider *)view;
            break;
        }
    }
    self.val = self.volumeViewSlider.value;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.volumeViewSlider setValue:0];
    });

}

- (void)soundBtnClick{
    _soundBtn.selected = !_soundBtn.selected;
    if(_soundBtn.selected) {
        self.val = self.volumeViewSlider.value;
        [_volumeViewSlider setValue:0];
    }else{
        [_volumeViewSlider setValue:_val];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self playVideo];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.player pause];
    [_timer invalidate];
    _timer = nil;
}

- (void)loginBtnClick{
    WEAKSELF
    [UIView animateWithDuration:0.5 animations:^{
        weakSelf.logoImage.frame = CGRectMake((DEVICE_WIDTH - 86) / 2, 18 + STATUSBAR_HEIGHT, 86, 20);
        weakSelf.loginView.frame = CGRectMake(0, 60 + STATUSBAR_HEIGHT, DEVICE_WIDTH, DEVICE_HEIGHT - (60 + STATUSBAR_HEIGHT));
        weakSelf.backBtn.hidden = NO;
        weakSelf.soundBtn.hidden = YES;
    }];
}

-(void)reciveBtnClick{
    KRTabarController *vc = [[KRTabarController alloc] init];
    UINavigationController *navVc = [[UINavigationController alloc] initWithRootViewController:vc];
    [UIApplication sharedApplication].delegate.window.rootViewController = navVc;
}

- (void)backBtnClick{
    if(_wxLoginBtn.hidden){
        _loginType = codeLogin;
        self.loginTitleLbl.text = @"验证码登录";
        [self.LoginTypeBtn setTitle:@"账号登录" forState:UIControlStateNormal];
        self.codeField.text = @"";
        self.codeField.placeholder = @"请输入验证码";
        [self.loginBtn setTitle:@"登录/注册" forState:UIControlStateNormal];
        _forgetLab.hidden = YES;
        _seeBtn.hidden = YES;
        _loginType = codeLogin;
        _codeBtn.hidden = NO;
        [_attributeLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_loginBtn.mas_bottom).offset(24);
            make.left.offset(56);
            make.right.offset(-24);
        }];
        _codeField.keyboardType = UIKeyboardTypeNumberPad;
        _leftLineimageView.hidden  =
        _rightLineimageView.hidden =
        _tipsLbl.hidden            =
        _select_icon.hidden        =
        _wxLoginBtn.hidden         =
        _LoginTypeBtn.hidden       =
        _attributeLbl.hidden       =
        _appleLoginBtn.hidden      = NO;
    }else{
        _photoField.text = @"";
        _codeField.text = @"";
        [self.view endEditing:YES];
        WEAKSELF
        [UIView animateWithDuration:0.5 animations:^{
            weakSelf.logoImage.frame = CGRectMake((DEVICE_WIDTH - 198) /2, 170 + STATUSBAR_HEIGHT, 198, 46);
            weakSelf.loginView.frame = CGRectMake(0, DEVICE_HEIGHT, DEVICE_WIDTH, DEVICE_HEIGHT - (60 + STATUSBAR_HEIGHT));
            weakSelf.backBtn.hidden = YES;
            weakSelf.soundBtn.hidden = NO;
        }];
    }
}

- (void)setupForAVplayerView
{
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.frame = self.view.frame;
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.view.layer addSublayer:playerLayer];
}

- (AVPlayerItem *)getPlayItem
{
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"keren" ofType:@"mp4"];
    NSURL *url = [NSURL fileURLWithPath:filePath];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
    return playerItem;
}

- (void)__playerItemDidPlayToEndTimeNotification:(NSNotification *)sender
{
    [_player seekToTime:kCMTimeZero]; // 设置从头继续播放
}

- (void)playVideo{
    if([[[ClassManager shareInstance] currentViewController] isKindOfClass:[LoginViewController class]]){
       // [self.volumeViewSlider setValue:0 animated:NO];
        [self.player play];
    }
}

- (AVPlayer *)player
{
    if (!_player) {
        AVPlayerItem *playerItem = [self getPlayItem];
        _player = [AVPlayer playerWithPlayerItem:playerItem];
        //设置重复播放
        _player.actionAtItemEnd = AVPlayerActionAtItemEndNone; // set this
        //视频播放完发通知
        [[NSNotificationCenter defaultCenter]addObserver:self
                                                selector:@selector(__playerItemDidPlayToEndTimeNotification:)
                                                    name:AVPlayerItemDidPlayToEndTimeNotification
                                                  object:nil];
    }
    return _player;
}

#pragma mark:登录
- (void)login{
    NSDictionary *parameters;
    switch (_loginType) {
        case WXLogin:
            break;
        case forgotPassword:
            [self checkCode];
            return;
            break;
        case codeLogin:
            if([[NSStringManager shareInstance] checkPhone:_photoField.text]){
                if(_codeField.text.length == 0){
                    [[KRAlartManager shareInstance] showErrorAlert:@"请输入验证码"];
                    return;
                }
                parameters = @{@"code":@([_codeField.text intValue]) ,@"phone":_photoField.text,@"type":@(1)};
            }else{
                return;
            }
            break;
        case passwordLogin:
            if([[NSStringManager shareInstance] checkPhone:_photoField.text] && [[NSStringManager shareInstance] judgePassWordLegal:_codeField.text]){
                parameters = @{@"password":_codeField.text,@"phone":_photoField.text,@"type":@(0)};
                DDLogInfo(@"%@",parameters);
            }else{
                return;
            }
            break;
        case setPassword:
            if(![_photoField.text isEqualToString:_codeField.text]){
                [[KRAlartManager shareInstance] showErrorAlert:@"新密码前后不一致，请重新设置"];
                return;
            }else{
                if([[NSStringManager shareInstance] judgePassWordLegal:_codeField.text]){
                    [self changePasswold];
                    return;
                }else{
                    return;
                }
            }
            break;
          case bindPhone:
            if([[NSStringManager shareInstance] checkPhone:_photoField.text]){
                if(_codeField.text.length == 0){
                    [[KRAlartManager shareInstance] showErrorAlert:@"请输入验证码"];
                    return;
                }else{
                    [self bindPhone];
                    return;
                }
               // parameters = @{@"code":@([_codeField.text intValue]) ,@"phone":_photoField.text,@"type":@(1)};
            }else{
                return;
            }
        default:
            break;
    }
    if(!_select_icon.selected || !setPassword){
        //TODO: 国际化
        [[KRAlartManager shareInstance] showErrorAlert:@"请阅读并同意相关政策"];
        return;
    }
    [[KRAlartManager shareInstance] showLodingAlertView:@"努力加载中..."];
    WEAKSELF
    [NetworkingTool POST:User_login parameters:parameters isDeviceUrl:NO success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        [[KRAlartManager shareInstance] hidenLodingImageView];
        if([response[@"code"] intValue] == 0){
            if(response[@"data"] && [response[@"data"] isKindOfClass:[NSDictionary class]]){
                NSDictionary *dict = response[@"data"];
                [[NSUserDefaults standardUserDefaults] setObject:dict forKey:USERINFOKEY];
                [[NSUserDefaults standardUserDefaults] setObject:weakSelf.photoField.text forKey:USERPHONE];

                [weakSelf reciveBtnClick];
            }
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

- (void)bindPhone{
    WEAKSELF
    [[KRAlartManager shareInstance] showLodingAlertView:@"努力加载中..."];
    NSDictionary *parameters = @{@"code":@([_codeField.text intValue]),@"phone":_photoField.text,@"third_party_account":_appleId};
    NSString *url = User_bind_appleId;
    if(_isbindWX){
        url = User_bind_wx;
    }
    [NetworkingTool POST:url parameters:parameters isDeviceUrl:NO success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            
            if(response[@"data"] && [response[@"data"] isKindOfClass:[NSDictionary class]]){
                NSDictionary *dict = response[@"data"];
                [[NSUserDefaults standardUserDefaults] setObject:dict forKey:USERINFOKEY];
                [[NSUserDefaults standardUserDefaults] setObject:weakSelf.photoField.text forKey:USERPHONE];

                [weakSelf reciveBtnClick];
            }else{
                [[KRAlartManager shareInstance] hidenLodingImageView];
                [weakSelf backBtnClick];
                [[KRAlartManager shareInstance] showAlert:@"绑定手机成功，请重新登录"];

            }
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];

}

- (void)checkCode{
    if(_photoField.text.length < 1){
        [[KRAlartManager shareInstance] showErrorAlert:@"请输入手机号"];
        return;
    }
    if(_codeField.text.length < 1){
        [[KRAlartManager shareInstance] showErrorAlert:@"请输入验证码"];
        return;
    }

    WEAKSELF
    NSDictionary *parameters = @{@"code":@([_codeField.text intValue]),@"phone":_photoField.text};
    [NetworkingTool POST:User_sms_check parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            weakSelf.code = weakSelf.codeField.text;
            weakSelf.phone = weakSelf.photoField.text;
            weakSelf.photoField.text = @"";
            weakSelf.codeField.text = @"";
            weakSelf.codeBtn.hidden = YES;
            weakSelf.seeBtn.hidden = YES;
            weakSelf.codeField.secureTextEntry = NO;
            weakSelf.loginTitleLbl.text = @"设置新密码";
            weakSelf.photoField.placeholder = @"请输入新密码";
            weakSelf.codeField.placeholder  = @"再次输入新密码";
            weakSelf.photoField.keyboardType = UIKeyboardTypeDefault;
            [weakSelf.loginBtn setTitle:@"确定" forState:UIControlStateNormal];
            weakSelf.loginType = setPassword;
        }else{
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

- (void)changePasswold{
    WEAKSELF
    NSDictionary *parameters = @{@"code":@([_code intValue]),@"phone":_phone,@"password":_codeField.text};
    [NetworkingTool POST:User_forgot_password parameters:parameters isDeviceUrl:NO success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            weakSelf.photoField.text = @"";
            [weakSelf backBtnClick];

        }else{
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

- (void)appleLogin{
    if(!_select_icon.selected || !setPassword){
        //TODO: 国际化
        [[KRAlartManager shareInstance] showErrorAlert:@"请阅读并同意相关政策"];
        return;
    }
    _isbindWX = NO;
    [[LoginManager sharedInstance] appleLogin];
}

-(void)otherLogin{
    [[LoginManager sharedInstance] checkUnlockSupportType];
}

- (void)wxLogin{
    if(!_select_icon.selected || !setPassword){
        //TODO: 国际化
        [[KRAlartManager shareInstance] showErrorAlert:@"请阅读并同意相关政策"];
        return;
    }
    _isbindWX = YES;
    [[LoginManager sharedInstance] wxLogin];
}

- (void)changeLoginType{
    self.codeField.text = @"";
    _photoField.keyboardType = UIKeyboardTypeNumberPad;
    if(_loginType == codeLogin){
        
        //TODO 国际化
        self.loginTitleLbl.text = @"账号登录";
        [self.LoginTypeBtn setTitle:@"验证码登录" forState:UIControlStateNormal];
        [self.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        self.codeField.placeholder = @"请输入密码";
        _seeBtn.hidden = NO;
        _loginType = passwordLogin;
        [_attributeLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_loginBtn.mas_bottom).offset(70);
            make.left.offset(56);
            make.right.offset(-24);
        }];
        _forgetLab.hidden = NO;
        _codeBtn.hidden = YES;
        _codeField.keyboardType = UIKeyboardTypeDefault;
        _codeField.secureTextEntry = YES;

    }else{
        //TODO 国际化
        self.loginTitleLbl.text = @"验证码登录";
        [self.LoginTypeBtn setTitle:@"账号登录" forState:UIControlStateNormal];
        self.codeField.placeholder = @"请输入验证码";
        [self.loginBtn setTitle:@"登录/注册" forState:UIControlStateNormal];
        _forgetLab.hidden = YES;
        _seeBtn.hidden = YES;
        _loginType = codeLogin;
        _codeBtn.hidden = NO;
        [_attributeLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_loginBtn.mas_bottom).offset(24);
            make.left.offset(56);
            make.right.offset(-24);
        }];
        _codeField.keyboardType = UIKeyboardTypeNumberPad;
        _codeField.secureTextEntry = NO;
    }
}

- (void)getPhoneCode{
    WEAKSELF
    if([[NSStringManager shareInstance] checkPhone:_photoField.text]){
        [[KRAlartManager shareInstance] showLodingAlertView:@"努力加载中..."];
        self.codeBtn.enabled = NO;
        NSDictionary *parameters = @{@"phone":_photoField.text};
        [NetworkingTool POST:Get_sms_code parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
            [[KRAlartManager shareInstance] hidenLodingImageView];
            if([response[@"code"] intValue] == 0){
                [weakSelf timer];
            }
        } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        }];
    }
    
}

- (void)getCodeTimeStr{
    _second --;
    [self.codeBtn setTitle:[NSString stringWithFormat:@"%lds",_second] forState:UIControlStateNormal];
    if(_second == 0){
        [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        self.codeBtn.enabled = YES;
        [_timer invalidate];
        _timer = nil;
    }
}

- (void)selecticonClick{
    _select_icon.selected = !_select_icon.selected;
}


- (void)setPhonenumb:(NSNotification *)notifacation{
    _appleId = notifacation.object;
    _loginType = bindPhone;
    _loginTitleLbl.text = @"请绑定手机号";
    _photoField.placeholder = @"请输入手机号";
    _codeField.placeholder = @"请输入验证码";
    _photoField.keyboardType = UIKeyboardTypeNumberPad;
    _forgetLab.hidden          =
    _leftLineimageView.hidden  =
    _rightLineimageView.hidden =
    _tipsLbl.hidden            =
    _select_icon.hidden        =
    _wxLoginBtn.hidden         =
    _LoginTypeBtn.hidden       =
    _attributeLbl.hidden       =
    _seeBtn.hidden             =
    _appleLoginBtn.hidden      = YES;
    _codeBtn.hidden = NO;
    [_loginBtn setTitle:@"下一步" forState:UIControlStateNormal];

}

- (void)forgetTipClick{
    _loginType = forgotPassword;
    _loginTitleLbl.text = @"忘记密码";
    _photoField.placeholder = @"请输入手机号";
    _codeField.placeholder = @"请输入验证码";
    _photoField.keyboardType = UIKeyboardTypeNumberPad;
    _forgetLab.hidden          =
    _leftLineimageView.hidden  =
    _rightLineimageView.hidden =
    _tipsLbl.hidden            =
    _select_icon.hidden        =
    _wxLoginBtn.hidden         =
    _LoginTypeBtn.hidden       =
    _attributeLbl.hidden       =
    _seeBtn.hidden             =
    _appleLoginBtn.hidden      = YES;
    _codeBtn.hidden = NO;
    _codeField.secureTextEntry = NO;

    [_loginBtn setTitle:@"下一步" forState:UIControlStateNormal];
}

- (void)seePassword{
    _seeBtn.selected = !_seeBtn.selected;
    _codeField.secureTextEntry = !_codeField.secureTextEntry;
}

- (UIView *)loginView{
    if(!_loginView){
        _loginView = [[UIView alloc] initWithFrame:CGRectMake(0, DEVICE_HEIGHT, DEVICE_WIDTH, DEVICE_HEIGHT - (60 + STATUSBAR_HEIGHT))];
        _loginType = codeLogin;
        [self.view addSubview:_loginView];
        _loginView.backgroundColor = Color_EEEEEE;
        _loginView.layer.mask = [CAShapeLayer clipsToBounds:_loginView.bounds Corners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(40, 40)];
        _loginTitleLbl = [[UILabel alloc] init];
        [_loginView addSubview:_loginTitleLbl];
        [_loginTitleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.offset(24);
        }];
        _loginTitleLbl.font = BFont(32);
        _loginTitleLbl.textColor = Black_Color;
        //TODO 国际化
        _loginTitleLbl.text = @"验证码登录";
        _LoginTypeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_loginView addSubview:_LoginTypeBtn];
        [_LoginTypeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.offset(-24);
            make.left.equalTo(_loginTitleLbl.mas_right).offset(24);
            make.height.offset(28);
            make.centerY.equalTo(_loginTitleLbl);
        }];
        //请输入手机号码
        //TODO 国际化
        [_LoginTypeBtn setTitle:@"账号登录" forState:UIControlStateNormal];
        [_LoginTypeBtn setImage:[UIImage imageNamed:@"Vector"] forState:UIControlStateNormal];
        _LoginTypeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [_LoginTypeBtn setTitleColor:Black_Color forState:UIControlStateNormal];
        _LoginTypeBtn.titleLabel.font = BFont(20);
        [_LoginTypeBtn setSemanticContentAttribute:UISemanticContentAttributeForceRightToLeft];
        _LoginTypeBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -4);
        _photoField = [UITextField setFlieldplaceholder:@"请输入手机号码" Font:Font(16) borderColor:Color_D0D3D4];
        [_loginView addSubview:_photoField];
        [_photoField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(92);
            make.left.offset(24);
            make.right.offset(-24);
            make.height.offset(72);
        }];
        _photoField.keyboardType = UIKeyboardTypeNumberPad;
        _photoField.rightViewMode = UITextFieldViewModeNever;
        _photoField.clearButtonMode = UITextFieldViewModeAlways;
        UIButton *clean = [_photoField valueForKey:@"_clearButton"]; //key是固定的
        [clean setImage:[UIImage imageNamed:@"clear"] forState:UIControlStateNormal];
        _codeField = [UITextField setFlieldplaceholder:@"请输入验证码" Font:Font(16) borderColor:Color_D0D3D4];
        //_codeField.secureTextEntry = YES;
        [_loginView addSubview:_codeField];
        [_codeField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(180);
            make.left.offset(24);
            make.right.offset(-24);
            make.height.offset(72);
        }];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)
                                                    name:@"UITextFieldTextDidChangeNotification"
                                                  object:_codeField];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)
                                                    name:@"UITextFieldTextDidChangeNotification"
                                                  object:_photoField];
        [_LoginTypeBtn addTarget:self action:@selector(changeLoginType) forControlEvents:UIControlEventTouchUpInside];
        
        _codeBtn = [UIButton setButtonWithTitle:@"获取验证码" titleColor:Color_7ACC00 titleFont:BFont(16) cornerRadius:0 backColor:[UIColor clearColor]];
        [_loginView addSubview:_codeBtn];
        [_codeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_codeField.mas_right).offset(-24);
            make.top.bottom.equalTo(_codeField);
        }];
        
        _seeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_loginView addSubview:_seeBtn];
        _seeBtn.hidden = YES;
        [_seeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_codeField.mas_right).offset(-10);
            make.width.height.offset(44);
            make.centerY.equalTo(_codeField);
        }];
        [_seeBtn setImage:[UIImage imageNamed:@"login_password_unsee"] forState:UIControlStateNormal];
        [_seeBtn setImage:[UIImage imageNamed:@"login_password_Hide"] forState:UIControlStateSelected];

        [_seeBtn addTarget:self action:@selector(seePassword) forControlEvents:UIControlEventTouchUpInside];
        [_codeBtn addTarget:self action:@selector(getPhoneCode) forControlEvents:UIControlEventTouchUpInside];
        _loginBtn = [UIButton setButtonWithTitle:@"登录/注册" titleColor:Whire_Color titleFont:Font(16) cornerRadius:25 backColor:Color_7ACC00];
        [_loginView addSubview:_loginBtn];
        [_loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(24);
            make.right.offset(-24);
            make.height.offset(58);
            make.top.equalTo(_codeField.mas_bottom).offset(40);
        }];
        [_loginBtn addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
        _forgetLab = [[UILabel alloc] init];
        [_loginView addSubview:_forgetLab];
        [_forgetLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(24);
            make.top.equalTo(_loginBtn.mas_bottom).offset(24);
        }];
        _forgetLab.font = Font(16);
        _forgetLab.textColor = Black_Color;
        _forgetLab.text = @"忘记密码？";
        _forgetLab.hidden = YES;
        UITapGestureRecognizer *forgetTip = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(forgetTipClick)];
        _forgetLab.userInteractionEnabled = YES;
        [_forgetLab addGestureRecognizer:forgetTip];
        
        _appleLoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_loginView addSubview:_appleLoginBtn];

        NSURL * weixin_App = [NSURL URLWithString:@"weixin://"];
        if ([[UIApplication sharedApplication] canOpenURL:weixin_App]){
            _wxLoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [_loginView addSubview:_wxLoginBtn];
            float spaceWidth = (DEVICE_WIDTH - 82 - 56 * 2) / 2;
            [_wxLoginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.offset(-36);
                make.width.height.offset(56);
                make.left.offset(spaceWidth);
            }];
            [_wxLoginBtn setImage:[UIImage imageNamed:@"WXLogo"] forState:UIControlStateNormal];
            [_wxLoginBtn addTarget:self action:@selector(wxLogin) forControlEvents:UIControlEventTouchUpInside];
            [_appleLoginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.offset(-36);
                make.width.height.offset(56);
                make.left.equalTo(_wxLoginBtn.mas_right).offset(82);
            }];
        }else{
            [_appleLoginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.offset(-36);
                make.width.height.offset(56);
                make.centerX.equalTo(self.view);
            }];
        }
        
        [_appleLoginBtn setImage:[UIImage imageNamed:@"appleLogo"] forState:UIControlStateNormal];
        [_appleLoginBtn addTarget:self action:@selector(appleLogin) forControlEvents:UIControlEventTouchUpInside];
        _tipsLbl = [[UILabel alloc] init];
        [_loginView addSubview:_tipsLbl];
        [_tipsLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(_appleLoginBtn.mas_top).offset(-16);
            make.centerX.equalTo(self.view);
            make.width.mas_greaterThanOrEqualTo(120);
        }];
        _tipsLbl.text = @"或者选择其他登录方式";
        _tipsLbl.textColor = Color_86898E;
        _tipsLbl.font = Font_Medium(14);
     
        _leftLineimageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tipLineimage_left"]];
        [_loginView addSubview:_leftLineimageView];
        [_leftLineimageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_tipsLbl);
            make.left.offset(24);
            make.right.equalTo(_tipsLbl.mas_left).offset(-12);
            make.height.offset(1);
        }];
        _rightLineimageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tipLineimage_right"]];
        [_loginView addSubview:_rightLineimageView];
        [_rightLineimageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_tipsLbl);
            make.right.offset(-24);
            make.left.equalTo(_tipsLbl.mas_right).offset(12);
            make.height.offset(1);
        }];
        
        _attributeLbl = [[UILabel alloc] init];
        [_loginView addSubview:_attributeLbl];
        [_attributeLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_loginBtn.mas_bottom).offset(24);
            make.left.offset(56);
            make.right.offset(-24);
        }];
        NSAttributedString *showAttString = [NSAttributedString getAttributeWith:@[@"《用户协议》",@"《隐私政策》"] string:@"我已阅读并同意《用户协议》、《隐私政策》，首次自动注册新账号。" Font:Font_Medium(14) Color:Color_86898E attributeFont:Font_Medium(14) attributeColor:Color_7ACC00];
        _attributeLbl.attributedText = showAttString;
        _attributeLbl.numberOfLines = 0;
        [_attributeLbl yb_addAttributeTapActionWithStrings:@[@"《用户协议》",@"《隐私政策》"] tapClicked:^(UILabel *label, NSString *string, NSRange range, NSInteger index) {
            if([string isEqualToString:@"《用户协议》"]){
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://%@/html/userAgreement.html",BaseHost]] options:@{} completionHandler:^(BOOL success) {
                }];
            }else{
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://%@/html/privacyAgreement.html",BaseHost]] options:@{} completionHandler:^(BOOL success) {
                }];
            }
        }];
        _select_icon = [UIButton buttonWithType:UIButtonTypeCustom];
        [_loginView addSubview:_select_icon];
        [_select_icon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(14);
            make.width.height.offset(40);
            make.top.mas_equalTo(_attributeLbl.mas_top).offset(-10);
        }];
        [_select_icon setImage:[UIImage imageNamed:@"select_icon_u"] forState:UIControlStateNormal];
        [_select_icon setImage:[UIImage imageNamed:@"select_icon_s"] forState:UIControlStateSelected];
        [_select_icon addTarget:self action:@selector(selecticonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginView;
}

- (NSTimer *)timer{
    if(!_timer){
        _second = 60;
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(getCodeTimeStr) userInfo:nil repeats:YES];
    }
    return _timer;
}

-(void)textFiledEditChanged:(NSNotification*)notification{
    UITextField *textField = notification.object;
    NSString *str = textField.text;
    if(notification.object == _photoField && (_loginType == passwordLogin || _loginType == codeLogin || _loginType == forgotPassword || _loginType == bindPhone)){
        if(str.length > 11){
            str =  [str substringToIndex:11];
        }
    }else{
        str = [NSString setPassWord:str];
    }
    textField.text = str;
}
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{

    UIMenuController *menuController = [UIMenuController sharedMenuController];
    if (menuController) {
        [UIMenuController sharedMenuController].menuVisible = NO;
    }
    return NO;
}
- (BOOL)canBecomeFirstResponder {
    return NO;
}

@end
